import 'package:flutter/material.dart';
import 'package:flutter_map/flutter_map.dart';
import 'package:get/get.dart';
import 'package:latlong2/latlong.dart';
import 'package:situation/app/theme/gaps.dart';
import 'package:situation/resources/assets.dart';
import 'package:situation/widgets/mk_load_image.dart';

class MapLineDraw extends StatefulWidget {
  const MapLineDraw({
    super.key,
    this.onLinesChanged,
    this.onSave,
    this.lineColor = Colors.blue,
    this.lineWidth = 3.0
  });

  final ValueChanged<List<List<LatLng>>>? onLinesChanged;
  final Function(List<LatLng>)? onSave;
  final Color lineColor;
  final double lineWidth;

  static late final GlobalKey<_MapLineDrawState> stateKey =
  GlobalKey<_MapLineDrawState>();

  static void startNewLine() => stateKey.currentState?._startNewLine();
  static void undoPoint() => stateKey.currentState?._undoPoint();
  static void addPoint(point) => stateKey.currentState?._addPoint(point);
  static void removeAll() => stateKey.currentState?._removeAll();

  @override
  State<MapLineDraw> createState() => _MapLineDrawState();
}

class _MapLineDrawState extends State<MapLineDraw> {
  final List<List<LatLng>> _lines = [];
  List<LatLng> _currentLine = [];
  int? _selectedLineIndex;

  // 关键修改1：增强线段清理逻辑
  void _cleanupInvalidLines() {
    _lines.removeWhere((line) => line.length < 2);
  }

  void _removeAll () {
    setState(() {
      _lines.clear();
      _currentLine.clear();
      _selectedLineIndex = null;
    });
  }

  void _startNewLine() {
    setState(() {
      _currentLine = [];
      _selectedLineIndex = null;
      _cleanupInvalidLines(); // 清理无效线段
    });
    widget.onLinesChanged?.call(_lines);
  }

  void _addPoint(LatLng point) {
    setState(() {
      _currentLine.add(point);

      // 关键修改2：精确管理线段存储
      if (_currentLine.length >= 2) {
        // 移除所有中间状态线段
        _lines.removeWhere((line) => line.length == _currentLine.length - 1);
        // 添加最新完整线段
        _lines.add(List.from(_currentLine));
      }
    });
    widget.onLinesChanged?.call(_lines);
  }

  void _undoPoint() {
    if (_currentLine.isNotEmpty) {
      setState(() {
        _currentLine.removeLast();

        // 关键修改3：精准清理关联线段
        if (_currentLine.isNotEmpty) {
          // 清理所有长度超过当前点数的线段
          _lines.removeWhere((line) => line.length > _currentLine.length);
        } else {
          // 清空时移除所有相关线段
          _lines.clear();
        }

        if (_currentLine.length == 1) {
          _currentLine.clear();
        }

        _cleanupInvalidLines(); // 最终清理
      });
      widget.onLinesChanged?.call(_lines);
    }
  }

  void _deleteLine(int index) {
    setState(() {
      _lines.removeAt(index);
      if (_selectedLineIndex == index) _selectedLineIndex = null;
    });
    widget.onLinesChanged?.call(_lines);
  }

  Widget _buildControlPanel() {
    return Positioned(
      right: 20,
      bottom: Get.height*0.4,
      child: Container(
        padding: _currentLine.isEmpty ? const EdgeInsets.all(0) :const EdgeInsets.all(8),
        decoration: BoxDecoration(
          color: Colors.black.withAlpha(80),
          borderRadius: BorderRadius.circular(8),
        ),
        child: Column(
          children: [
            if (_currentLine.isNotEmpty) ...[
              _buildIconButton(
                  icon: Icons.save,
                  color: Colors.blue,
                  onPressed: () {
                    if (_currentLine.length < 2) return;
                    widget.onSave?.call(_currentLine);
                    _startNewLine();
                  }
              ),
              Gaps.vGap8,
              _buildIconButton(
                  icon: Icons.undo,
                  color: Colors.orange,
                  onPressed: _undoPoint
              ),
              Gaps.vGap8,
              _buildIconButton(
                  icon: Icons.delete,
                  color: Colors.red,
                  onPressed: () => _deleteSelectedLine()
              ),
            ],

          ],
        ),
      ),
    );
  }

  Widget _buildIconButton({
    required IconData icon,
    required Color color,
    required VoidCallback onPressed
  }) {
    return GestureDetector(
      onTap: onPressed,
      child: Container(
        padding: EdgeInsets.all(6),
        decoration: BoxDecoration(
          color: Colors.white,
          shape: BoxShape.circle,
        ),
        child: Icon(icon, size: 20, color: color),
      ),
    );
  }

  void _deleteSelectedLine() {
    if (_selectedLineIndex != null) {
      _deleteLine(_selectedLineIndex!);
    }
  }

  @override
  Widget build(BuildContext context) {
    return Stack(
      children: [
        // 关键修改4：严格过滤渲染条件
        PolylineLayer(
          polylines: [
            for (final line in _lines.where((l) => l.length >= 2))
              Polyline(
                points: line,
                color: widget.lineColor,
                strokeWidth: widget.lineWidth,
              ),
          ],
        ),

        MarkerLayer(
          markers: [
            if (_currentLine.isNotEmpty)
              for (final point in _currentLine)
                Marker(
                  width: 20,
                  height: 20,
                  point: point,
                  child: Icon(Icons.circle, size: 20,color: Colors.blue,),
                ),
          ],
        ),

        if (_currentLine.length >= 2)
          PolylineLayer(
            polylines: [
              Polyline(
                points: _currentLine,
                color: widget.lineColor.withAlpha(150),
                strokeWidth: widget.lineWidth,
              ),
            ],
          ),

        _buildControlPanel(),
      ],
    );
  }
}
